package com.up.stores.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.up.stores.entity.Bussinessman;
import com.up.stores.entity.User;
import com.up.stores.mapper.BussinessmanMapper;
import com.up.stores.service.IBaseBussService;
import com.up.stores.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

@Service
public class BaseBusServiceImpl implements IBaseBussService {
    @Autowired
    BussinessmanMapper bussinessmanMapper;

    @Override
    public void reg(String realName, String username, String password, String password2, String phone, String email) {
        QueryWrapper<Bussinessman> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bus_name", username);
        Bussinessman result = bussinessmanMapper.selectOne(queryWrapper);

        if(result !=null){
            throw new UsernameDuplicateException("该用户名已存在");
        }

        //检测两次输入的密码是否相同
        if(!password.equals(password2)){
            throw new PasswordNotMatchException("两次输入的密码不同");
        }

        Bussinessman bussinessman = new Bussinessman();
        //密码加密处理实现——MD5算法加密，连续加载三次
        //盐值——随机字符串
        String oldPassword = password;
        bussinessman.getPassword();
        //获取盐值并随机字符串盐值
        String salt = UUID.randomUUID().toString().toUpperCase();
        //不数据，盐值的记录
        bussinessman.setSalt(salt);
        //将密码和盐值作为整体做加密处理
        String md5Password = getMD5Password(oldPassword,salt);
        //将加密后的密码重新不全到bussinessman对象中
        bussinessman.setPassword(md5Password);
        //补全数据
        bussinessman.setRealName(realName);
        bussinessman.setBusName(username);
        bussinessman.setEmail(email);
        bussinessman.setPhone(phone);
        //补全数据：is_delete设置成0
        bussinessman.setIsDelete(0);
        //补全数据的四个日志字段信息
        bussinessman.setCreatedUser(bussinessman.getBusName());
        bussinessman.setModifiedUser(bussinessman.getBusName());
        Date date = new Date();
        bussinessman.setCreatedTime(date);
        bussinessman.setModifiedTime(date);

        //执行注册业务功能的实现（rows==1）
        Integer rows = bussinessmanMapper.insert(bussinessman);
        if (rows != 1) {
            throw new InsertException("在用户注册过程中产生了未知的异常");
        }
    }

    @Override
    public Bussinessman login(String username, String password) {
        QueryWrapper<Bussinessman> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("bus_name",username);
        Bussinessman result=bussinessmanMapper.selectOne(queryWrapper);
        if(result==null){
            //不存在,姓名错误
            throw new UserNotFoundException("用户不存在");
        }
        if(result.getIsDelete()==1){
            //注销了
            throw new UserIsdeleteException("用户已注销");
        }
        String salt=result.getSalt();
        String Md5password=getMD5Password(password,salt);

        System.out.println(salt);
        System.out.println(password);
        System.out.println(Md5password);
        System.out.println(result.getPassword());

        if(!result.getPassword().equals(Md5password)){
            //登入的密码错误
            throw new PasswordNotMatchException("密码错误");
        }
        Bussinessman bussinessman=new Bussinessman();
        bussinessman.setBusName(username);
        bussinessman.setAvatar(result.getAvatar());
        bussinessman.setBusId(result.getBusId());
        return bussinessman;
    }

    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword, String newPassword2) {
        QueryWrapper<Bussinessman> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bus_id", uid);
        Bussinessman result = bussinessmanMapper.selectOne(queryWrapper);

        if(result==null){
            //用户数据不存在
            throw new UserNotFoundException("用户不存在");
        }
        if(result.getIsDelete()==1){
            //用户已经注销
            throw new UserIsdeleteException("用户已注销");
        }

        String salt = result.getSalt();
        String Md5password = getMD5Password(oldPassword, salt);

        if(!result.getPassword().equals(Md5password)){
            //输入的原密码错误
            throw new PasswordNotMatchException("原密码错误");
        }

        if(!newPassword.equals(newPassword2)){
            throw new PasswordNotMatchException("两次输入的密码不同");
        }

        //重新组装数据
        String NewMd5Password = getMD5Password(newPassword,salt);
        Date now=new Date();
        Bussinessman bussinessman = new Bussinessman();
        bussinessman.setPassword(newPassword);
        bussinessman.setModifiedUser(result.getBusName());
        bussinessman.setModifiedTime(now);
        bussinessman.setPassword(NewMd5Password);
        //更新数据
        //把名字为rhb的用户年龄更新为18，其他属性不变
        UpdateWrapper<Bussinessman> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("bus_id",result.getBusId());
        bussinessmanMapper.update(bussinessman, updateWrapper);
        return;
    }

    @Override
    public void changeAvatar(Integer uid, String username, String avatar) {
        Bussinessman user=bussinessmanMapper.selectById(uid);
        if(user==null){
            throw new UserNotFoundException("用户数据不存在");
        }
        if(user.getIsDelete().equals(1)){
            throw new UserNotFoundException("用户数据不存在");
        }
        Date date = new Date();
        QueryWrapper<Bussinessman> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bus_id",uid);
        user.setAvatar(avatar);
        user.setModifiedTime(date);
        bussinessmanMapper.update(user,queryWrapper);
    }

    @Override
    public Bussinessman getByUid(Integer uid) {
        QueryWrapper<Bussinessman> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bus_id",uid);
        Bussinessman result=bussinessmanMapper.selectOne(queryWrapper);
        return result;
    }

    @Override
    public void changeInfo(Bussinessman bus, Integer uid) {
        UpdateWrapper<Bussinessman> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("bus_id", uid);
        bussinessmanMapper.update(bus, updateWrapper);
    }


    //声明MD5加密处理
    private String getMD5Password(String password, String salt) {

        for (int i = 0; i < 3; i++) {
            //MD5加密算法调用，三次加密
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;
    }
}
